package com.ly.hotel.view.fragments.vod;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import java.lang.ref.WeakReference;
import java.util.Date;
import java.util.Formatter;
import java.util.Locale;
import com.ly.hotel.R;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.common.MyKeyEventCode;
import com.ly.hotel.common.MyLogsManager;
import com.ly.hotel.model.AdDetail;
import com.ly.hotel.msgevent.SendLogEvent;
import com.ly.hotel.util.DateUtils;
import com.ly.hotel.util.TouchUtil;
import com.ly.hotel.adaptor.HardwareInterface;
import com.ly.hotel.view.common.AdData;
import com.ly.hotel.view.common.CloudAdDialog;

import de.greenrobot.event.EventBus;

/**
 * 自定义MediaController，用于原生的MediaPlayer，具有支持自定义UI的特性。 使用方法：
 * 实现MediaControllerGenerator接口，该接口包含一个方法：
 * {@link MediaControllerGenerator#generateMediaController()}
 * 该方法从自定义的xml布局文件生成控制面板的布局，并且生成控制面板中的控件集合。 控制控件集合对应的类为
 * ，包含用于控制MediaPlayer的各种操作按钮和选项。
 * 
 */
public class NativeMediaController extends FrameLayout {
	private static final String TAG = "VideoControllerView";

	private MediaPlayerControl mPlayer;
	private Context mContext;
	private ViewGroup mAnchor;
	private View mRoot;
	private SeekBar mProgress;
	private SeekBar mVolumeBar;
	private ImageButton mMuteButtom;
	private TextView mEndTime, mCurrentTime;
	private boolean mShowing;
	private boolean mDragging;
	private static final int sDefaultTimeout = 5000;
	private static final int FADE_OUT = 1;
	private static final int SHOW_PROGRESS = 2;
	private static final int SET_VOLUME = 3;
	private static final int SHOW_AD = 4;
	private boolean mUseFastForward;
	private boolean mFromXml;
	private boolean mListenersSet;
	private OnClickListener mNextListener, mPrevListener;
	StringBuilder mFormatBuilder;
	Formatter mFormatter;
	private ImageButton mPauseButton;
	private TextView mTimeView;
	private ImageButton mFfwdButton;
	private ImageButton mRewButton;
	private ImageButton mNextButton;
	private ImageButton mPrevButton;
//	private ImageButton mFullscreenButton;
//	private ImageButton mMenuButton;
	private ImageButton mReturnButton;
	private View mParent;
	private int mPauseBtnResId, mMenuBtnResId, mReturnBtnResId, mStartBtnResId, mFullScreenResId, mUnFullScreenResId, mMenuResId;
	private Handler mHandler = new MessageHandler(this);
	public MyApplication app;
	
	private int maxVolume = 100;
	private int currentVolume = 5; 
	private int oldVolume = 0; 
	public boolean isVolumeMute = false;

	/**
	 * 公共接口：自定义控制条布局生成
	 */
	public interface MediaControllerGenerator {
		/**
		 * 从布局文件生成一个控制条的自定义布局
		 * 
		 * @return BaseMediaControllerHolder对象，控制条控件的集合
		 */
		BaseMediaControllerHolder generateMediaController();
	}

	private MediaControllerGenerator mUIGenerator;

	public void setUIGenerator(MediaControllerGenerator generator) {
		Log.i("medio", "setUIGenerator");
		this.mUIGenerator = generator;
		this.currentVolume = HardwareInterface.getVolume();
	}

	public NativeMediaController(Context context, AttributeSet attrs) {
		super(context, attrs);
		mRoot = null;
		mContext = context;
		mUseFastForward = true;
		mFromXml = true;
		Log.i(TAG, TAG);
	}

	public NativeMediaController(Context context, boolean useFastForward) {
		super(context);
		mContext = context;
		mUseFastForward = useFastForward;

		Log.i(TAG, TAG);
	}

	public NativeMediaController(Context context) {
		this(context, true);

		Log.i(TAG, TAG);
	}

	/*@Override
	public void onFinishInflate() {
		if (mRoot != null)
			initControllerView(mRoot);
	}*/

	@Override
	protected void onFinishInflate() {
		super.onFinishInflate();
		if (mRoot != null)
			initControllerView(mRoot);
	}

	public void setMediaPlayer(MediaPlayerControl player) {
		mPlayer = player;
		updatePausePlay();
//		updateFullScreen();
		initMenu();
	}

	/**
	 * Set the view that acts as the anchor for the control view. This can for
	 * example be a VideoView, or your Activity's main view.
	 * 
	 * @param view
	 *            The view to which to anchor the controller when it is visible.
	 */
	public void setAnchorView(ViewGroup view) {
		mAnchor = view;

		LayoutParams frameParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.MATCH_PARENT);

		removeAllViews();
		View v = makeControllerView();
		addView(v, frameParams);
	}

	/**
	 * Create the view that holds the widgets that control playback. Derived
	 * classes can override this to create their own.
	 * 
	 * @return The controller view.
	 */
	protected View makeControllerView() {
		if (mUIGenerator != null) {
			initControllerView(mUIGenerator.generateMediaController());
		} else {
			LayoutInflater inflate = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			mRoot = inflate.inflate(R.layout.video_native_media_controller, null);
			initControllerView(mRoot);
		}

		return mRoot;
	}

	private void initControllerView(BaseMediaControllerHolder holder) {
		app = holder.app;
		mRoot = holder.parentLayout;
		mPauseBtnResId = holder.pauseResId;
		mStartBtnResId = holder.startResId;
		mReturnBtnResId = holder.returnResId;
		mMenuBtnResId = holder.menuResId;
		mFullScreenResId = holder.fullscreenResId;
		mUnFullScreenResId = holder.unfullscreenResId;
		mMenuResId = holder.menuResId;

		mTimeView = holder.timeView;
		
		if(!MyApplication.isSupportRemote){
			mPauseButton = holder.pauseButton;
			if (mPauseButton != null) {
				mPauseButton.requestFocus();
				mPauseButton.setOnClickListener(mPauseListener);
			}
		} else {
			//在遥控器界面，需要隐藏这个按键
			holder.pauseButton.setVisibility(View.INVISIBLE);
		}
		if(!MyApplication.isSupportRemote){
			mReturnButton = holder.returnButton;
			if (mReturnButton != null) {
				mReturnButton.setImageResource(mReturnBtnResId);
				mReturnButton.requestFocus();
				mReturnButton.setOnClickListener(mReturnListener);
			}
		} else {
			//在遥控器界面，需要隐藏这个按键
			holder.returnButton.setVisibility(View.INVISIBLE);
		}
		
//		mFullscreenButton = holder.fullScreenButton;
//		if (mFullscreenButton != null) {
//			mFullscreenButton.requestFocus();
//			mFullscreenButton.setOnClickListener(mFullscreenListener);
//		}

//		mMenuButton = holder.menuButton;
//		if (mMenuButton != null) {
//			mMenuButton.setImageResource(mMenuBtnResId);
//			mMenuButton.requestFocus();
//			mMenuButton.setOnClickListener(mMenuListener);
//		}

		mParent = holder.parentLayout;
		if (mParent != null) {
			mParent.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					hide();
				}
			});
		}

		mFfwdButton = holder.forwardButton;
		if (mFfwdButton != null) {
			mFfwdButton.setOnClickListener(mFfwdListener);
			if (!mFromXml) {
				mFfwdButton.setVisibility(mUseFastForward ? View.VISIBLE : View.GONE);
			}
		}
		//暂停使用静音
		mMuteButtom = holder.muteButton;
		/*if (mMuteButtom != null) {
			mMuteButtom.requestFocus();
			mMuteButtom.setOnClickListener(mMuteListener);
		}*/
 
		mRewButton = holder.backwardButton;
		if (mRewButton != null) {
			mRewButton.setOnClickListener(mRewListener);
			if (!mFromXml) {
				mRewButton.setVisibility(mUseFastForward ? View.VISIBLE : View.GONE);
			}
		}

		// By default these are hidden. They will be enabled when
		// setPrevNextListeners() is called
		mNextButton = holder.nextButton;
		if (mNextButton != null && !mFromXml && !mListenersSet) {
			mNextButton.setVisibility(View.GONE);
		}
		mPrevButton = holder.preButton;
		if (mPrevButton != null && !mFromXml && !mListenersSet) {
			mPrevButton.setVisibility(View.GONE);
		}

		mProgress = holder.seekbar;
		if (mProgress != null) {
			if (mProgress instanceof SeekBar) {
				SeekBar seeker = (SeekBar) mProgress;
				seeker.setOnSeekBarChangeListener(mSeekListener);
			}
			mProgress.setMax(1000);
		}

		mVolumeBar = holder.volumeSeekbar;
		if (mVolumeBar != null) {
			
			maxVolume = HardwareInterface.getMaxVolume();
			
			Log.i("volume", "最大音量:" + maxVolume + ",当前音量:" + currentVolume);

			// 设置音量
			mVolumeBar.setMax(maxVolume);
			Log.i("volume", "setProgress begin");
			mVolumeBar.setProgress(currentVolume);
			Log.i("volume", "setProgress end");

			if (mVolumeBar instanceof SeekBar) {
				SeekBar seeker = (SeekBar) mVolumeBar;
				seeker.setOnSeekBarChangeListener(mVolumeBarListener);
			}
			// mVolumeBar.setProgress(currentVolume+1);

			// mVolumeBar.setMax(100);
		}

		mEndTime = holder.totalTimeView;
		mCurrentTime = holder.currentTimeView;
		mFormatBuilder = new StringBuilder();
		mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());

		installPrevNextListeners();
		//开始不要显示控制页面
//		show();
	}

	private void initControllerView(View v) {
		mPauseButton = (ImageButton) v.findViewById(R.id.pause);
		if (mPauseButton != null) {
			mPauseButton.requestFocus();
			mPauseButton.setOnClickListener(mPauseListener);
		}

//		mFullscreenButton = (ImageButton) v.findViewById(R.id.fullscreen);
//		if (mFullscreenButton != null) {
//			mFullscreenButton.requestFocus();
//			mFullscreenButton.setOnClickListener(mFullscreenListener);
//		}

		mFfwdButton = (ImageButton) v.findViewById(R.id.ffwd);
		if (mFfwdButton != null) {
			mFfwdButton.setOnClickListener(mFfwdListener);
			if (!mFromXml) {
				mFfwdButton.setVisibility(mUseFastForward ? View.VISIBLE : View.GONE);
			}
		}

		mRewButton = (ImageButton) v.findViewById(R.id.rew);
		if (mRewButton != null) {
			mRewButton.setOnClickListener(mRewListener);
			if (!mFromXml) {
				mRewButton.setVisibility(mUseFastForward ? View.VISIBLE : View.GONE);
			}
		}

		// By default these are hidden. They will be enabled when
		// setPrevNextListeners() is called
		mNextButton = (ImageButton) v.findViewById(R.id.next);
		if (mNextButton != null && !mFromXml && !mListenersSet) {
			mNextButton.setVisibility(View.GONE);
		}
		mPrevButton = (ImageButton) v.findViewById(R.id.prev);
		if (mPrevButton != null && !mFromXml && !mListenersSet) {
			mPrevButton.setVisibility(View.GONE);
		}

		mProgress = (SeekBar) v.findViewById(R.id.mediacontroller_progress);
		if (mProgress != null) {
			if (mProgress instanceof SeekBar) {
				SeekBar seeker = (SeekBar) mProgress;
				seeker.setOnSeekBarChangeListener(mSeekListener);
			}
			mProgress.setMax(1000);
		}

		mEndTime = (TextView) v.findViewById(R.id.time);
		mCurrentTime = (TextView) v.findViewById(R.id.time_current);
		mFormatBuilder = new StringBuilder();
		mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());

		installPrevNextListeners();
		show();
	}

	/**
	 * Show the controller on screen. It will go away automatically after 3
	 * seconds of inactivity.
	 */
	public void show() {
		show(sDefaultTimeout);
	}

	/**
	 * Disable pause or seek buttons if the stream cannot be paused or seeked.
	 * This requires the control interface to be a MediaPlayerControlExt
	 */
	private void disableUnsupportedButtons() {
		if (mPlayer == null) {
			return;
		}

		try {
			if (mPauseButton != null && !mPlayer.canPause()) {
				mPauseButton.setEnabled(false);
			}
			if (mRewButton != null && !mPlayer.canSeekBackward()) {
				mRewButton.setEnabled(false);
			}
			if (mFfwdButton != null && !mPlayer.canSeekForward()) {
				mFfwdButton.setEnabled(false);
			}
		} catch (IncompatibleClassChangeError ex) {
			// We were given an old version of the interface, that doesn't have
			// the canPause/canSeekXYZ methods. This is OK, it just means we
			// assume the media can be paused and seeked, and so we don't
			// disable
			// the buttons.
		}
	}

	/**
	 * Show the controller on screen. It will go away automatically after
	 * 'timeout' milliseconds of inactivity.
	 * 
	 * @param timeout
	 *            The timeout in milliseconds. Use 0 to show the controller
	 *            until hide() is called.
	 */
	public void show(int timeout) {
		if (!mShowing && mAnchor != null) {
			setProgress();
			if (mPauseButton != null) {
				mPauseButton.requestFocus();
			}
			disableUnsupportedButtons();

			LayoutParams tlp = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
					ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM);
			mAnchor.removeView(this);
			mAnchor.addView(this, tlp);
			mShowing = true;
		}
		if(MyApplication.shareUid != null && MyApplication.shareUid.equals("android.uid.system")){
			if(mTimeView != null){
				mTimeView.setText(DateUtils.getTimeString(new Date(),getResources()));
			}
		} else {
			if(mTimeView != null){
				mTimeView.setVisibility(View.INVISIBLE);
			}
		}
		updatePausePlay();
//		updateFullScreen();
		initMenu();
		// cause the progress bar to be updated even if mShowing
		// was already true. This happens, for example, if we're
		// paused with the progress bar showing the user hits play.
		mHandler.sendEmptyMessage(SHOW_PROGRESS);

		Message msg = mHandler.obtainMessage(FADE_OUT);
		if (timeout != 0) {
			mHandler.removeMessages(FADE_OUT);
			mHandler.sendMessageDelayed(msg, timeout);
		}
		
		if(mVolumeBar != null){
			mVolumeBar.setProgress(currentVolume);
		}
	}

	public boolean isShowing() {
		return mShowing;
	}

	/**
	 * Remove the controller from the screen.
	 */
	public void hide() {
		if (mAnchor == null) {
			return;
		}

		try {
			mAnchor.removeView(this);
			mHandler.removeMessages(SHOW_PROGRESS);
		} catch (IllegalArgumentException ex) {
			Log.w("MediaController", "already removed");
		}
		mShowing = false;
	}

	private String stringForTime(int timeMs) {
		int totalSeconds = timeMs / 1000;

		int seconds = totalSeconds % 60;
		int minutes = (totalSeconds / 60) % 60;
		int hours = totalSeconds / 3600;

		mFormatBuilder.setLength(0);
		if (hours > 0) {
			return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
		} else {
			return mFormatter.format("%02d:%02d", minutes, seconds).toString();
		}
	}

	private int setProgress() {
		if (mPlayer == null || mDragging) {
			return 0;
		}

		int position = mPlayer.getCurrentPosition();
		int duration = mPlayer.getDuration();
		if (mProgress != null) {
			if (duration > 0) {
				// use long to avoid overflow
				long pos = 1000L * position / duration;
				mProgress.setProgress((int) pos);
			}
			int percent = mPlayer.getBufferPercentage();
			mProgress.setSecondaryProgress(percent * 10);
		}

		if (mEndTime != null)
			mEndTime.setText(stringForTime(duration));
		if (mCurrentTime != null)
			mCurrentTime.setText(stringForTime(position));

		if (mVolumeBar != null) {
			mVolumeBar.setProgress(currentVolume);
		}
		return position;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		show(sDefaultTimeout);
		return true;
	}

	@Override
	public boolean onTrackballEvent(MotionEvent ev) {
		show(sDefaultTimeout);
		return false;
	}

	public boolean myOnKeyDown(int keyCode, KeyEvent event) {
		if (mPlayer == null) {
			return true;
		}
		Log.i("medio", "myOnKeyDown,keycode=" + keyCode);
		final boolean uniqueDown = event.getRepeatCount() == 0 && event.getAction() == KeyEvent.ACTION_DOWN;
		
		if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER){
			show(sDefaultTimeout);
			return true;
		}/*else if(keyCode == MyKeyEventCode.KEYCODE_PLAY_STOP){
			if (uniqueDown && !mPlayer.isPlaying()) {
				mPlayer.start();
				updatePausePlay();
				show(sDefaultTimeout);
			}else if (uniqueDown && mPlayer.isPlaying()) {
				mPlayer.pause();
				updatePausePlay();
				show(sDefaultTimeout);
			}
			return true;
		}*/else if(keyCode == KeyEvent.KEYCODE_DPAD_DOWN){
			show(sDefaultTimeout);
			HardwareInterface.setVolume(--currentVolume);
			mVolumeBar.setProgress(currentVolume);
			return true;
		}else if(keyCode == KeyEvent.KEYCODE_DPAD_UP){
			show(sDefaultTimeout);
			HardwareInterface.setVolume(++currentVolume);
			mVolumeBar.setProgress(currentVolume);
			return true;
		}else if (keyCode == MyKeyEventCode.KEYCODE_MUTE) {
			Log.i("music", "getVolume：" + HardwareInterface.getVolume());
			if(HardwareInterface.getVolume() != 0){
				oldVolume = HardwareInterface.getVolume();
				currentVolume = 0;
//				mVolumeBar.setProgress(0);
			}else{
//				mVolumeBar.setProgress(oldVolume);
				currentVolume = oldVolume;
			}
			if(mHandler.hasMessages(SET_VOLUME)){
				mHandler.removeMessages(SET_VOLUME);
			}
			mHandler.sendEmptyMessage(SET_VOLUME);
			return true;
		}else if(keyCode == KeyEvent.KEYCODE_DPAD_LEFT){//快退
			show(sDefaultTimeout);
			if (mPlayer != null) {
				if (mPlayer.getCurrentPosition() >= 0) {
					mPlayer.seekTo(mPlayer.getCurrentPosition() - 15000);
					System.out.println(mPlayer.getCurrentPosition());
				}
				if (mPlayer.getCurrentPosition() <= 0) {
					mPlayer.start();
				}

				if (mCurrentTime != null)
					mCurrentTime.setText(stringForTime((int) mPlayer.getCurrentPosition()));
				
				setProgress();
			}
			return true;
		}else if(keyCode == KeyEvent.KEYCODE_DPAD_RIGHT){//快进
			show(sDefaultTimeout);
			if (mPlayer != null) {
				if (mPlayer.getCurrentPosition() >= 0) {
					mPlayer.seekTo(mPlayer.getCurrentPosition() + 15000);
					System.out.println(mPlayer.getCurrentPosition());
				}
				if (mPlayer.getCurrentPosition() >= mPlayer.getDuration()) {
					mPlayer.seekTo(mPlayer.getDuration());
				}
				
				if (mCurrentTime != null)
					mCurrentTime.setText(stringForTime((int) mPlayer.getCurrentPosition()));
				
				setProgress();
			}
			return true;
		}else if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (uniqueDown && isShowing()) {
				hide();
				return true;
			}else{
				return false;
			}
		}

		return false;
	}

	private OnClickListener mPauseListener = new OnClickListener() {
		public void onClick(View v) {
			doPauseResume();
			show(sDefaultTimeout);
		}
	};

	private OnClickListener mReturnListener = new OnClickListener() {
		public void onClick(View v) {
			mParent.performClick();
			
			if(mHandler.hasMessages(SHOW_AD)){
				mHandler.removeMessages(SHOW_AD);
			}
			EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_VOD_PREFIX + "按下返回键"));
			TouchUtil.sendKeyCode(KeyEvent.KEYCODE_BACK,0, true);
		}
	};
	
	private OnClickListener mFullscreenListener = new OnClickListener() {
		public void onClick(View v) {
			doToggleFullscreen();
			show(sDefaultTimeout);
			System.out.println("mFullscreenListener");
		}
	};

/*	private OnClickListener mMenuListener = new OnClickListener() {
		public void onClick(View v) {
			System.out.println("mMenuListener");
			show(sDefaultTimeout);
			showBottomMenu();
		}
	};*/

	private OnClickListener mMuteListener = new OnClickListener() {
		public void onClick(View v) {
			if (!isVolumeMute) {
				isVolumeMute = true;
				currentVolume = mVolumeBar.getProgress();// 保存音量
				Log.i("volume", "当前音量:" + currentVolume);
				mVolumeBar.setProgress(0);
				mMuteButtom.setBackgroundResource(R.drawable.music_novolume);
			} else {
				// currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
				Log.i("volume", "当前音量:" + currentVolume);
				// 一定要先isVolumeMute = false;因为setProgress在这里是无效的，起到触发OnSeekBarChangeListener事件，实际上实在改时间完成更新的
				isVolumeMute = false;
				mVolumeBar.setProgress(currentVolume);
//				mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0);
				HardwareInterface.setVolume(currentVolume);
				mMuteButtom.setBackgroundResource(R.drawable.music_volume);
			}
		}
	};

	public void updatePausePlay() {
		if (mRoot == null || mPauseButton == null || mPlayer == null) {
			return;
		}

		if (mPlayer.isPlaying()) {
			mPauseButton.setImageResource(mPauseBtnResId);
		} else {
			mPauseButton.setImageResource(mStartBtnResId);
		}
	}

//	public void updateFullScreen() {
//		if (mRoot == null || mFullscreenButton == null || mPlayer == null) {
//			return;
//		}
//
//		if (mPlayer.isFullScreen()) {
//			mFullscreenButton.setImageResource(mUnFullScreenResId);
//		} else {
//			mFullscreenButton.setImageResource(mFullScreenResId);
//		}
//	}

	public void initMenu() {
//		if (mRoot == null || mMenuButton == null || mPlayer == null) {
//			return;
//		}
//
//		mMenuButton.setImageResource(mMenuResId);
	}

	private void doPauseResume() {
		if (mPlayer == null) {
			return;
		}

		if (mPlayer.isPlaying()) {
			mPlayer.pause();
			mHandler.sendEmptyMessageDelayed(SHOW_AD, 1500);
			EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_VOD_PREFIX + "暂停"));
		} else {
			if(mHandler.hasMessages(SHOW_AD)){
				mHandler.removeMessages(SHOW_AD);
			}
			mPlayer.start();
			EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_VOD_PREFIX + "播放"));
		}
		updatePausePlay();
	}

	private void doToggleFullscreen() {
		if (mPlayer == null) {
			return;
		}

		mPlayer.toggleFullScreen();
	}

	// There are two scenarios that can trigger the seekbar listener to trigger:
	//
	// The first is the user using the touchpad to adjust the posititon of the
	// seekbar's thumb. In this case onStartTrackingTouch is called followed by
	// a number of onProgressChanged notifications, concluded by
	// onStopTrackingTouch.
	// We're setting the field "mDragging" to true for the duration of the
	// dragging
	// session to avoid jumps in the position in case of ongoing playback.
	//
	// The second scenario involves the user operating the scroll ball, in this
	// case there WON'T BE onStartTrackingTouch/onStopTrackingTouch
	// notifications,
	// we will simply apply the updated position without suspending regular
	// updates.
	private OnSeekBarChangeListener mSeekListener = new OnSeekBarChangeListener() {
		public void onStartTrackingTouch(SeekBar bar) {
			show(3600000);

			mDragging = true;

			// By removing these pending progress messages we make sure
			// that a) we won't update the progress while the user adjusts
			// the seekbar and b) once the user is done dragging the thumb
			// we will post one of these messages to the queue again and
			// this ensures that there will be exactly one message queued up.
			mHandler.removeMessages(SHOW_PROGRESS);
		}

		public void onProgressChanged(SeekBar bar, int progress, boolean fromuser) {
			if (mPlayer == null) {
				return;
			}

			if (!fromuser) {
				// We're not interested in programmatically generated changes to
				// the progress bar's position.
				return;
			}

			long duration = mPlayer.getDuration();
			long newposition = (duration * progress) / 1000L;
			mPlayer.seekTo((int) newposition);
			if (mCurrentTime != null)
				mCurrentTime.setText(stringForTime((int) newposition));
		}

		public void onStopTrackingTouch(SeekBar bar) {
			mDragging = false;
			setProgress();
			updatePausePlay();
			show(sDefaultTimeout);

			// Ensure that progress is properly updated in the future,
			// the call to show() does not guarantee this because it is a
			// no-op if we are already showing.
			mHandler.sendEmptyMessage(SHOW_PROGRESS);
		}
	};

	private OnSeekBarChangeListener mVolumeBarListener = new OnSeekBarChangeListener() {
		public void onStartTrackingTouch(SeekBar bar) {
			show(3600000);
			//会导致视频进度天停止
//			mDragging = true;

			// By removing these pending progress messages we make sure
			// that a) we won't update the progress while the user adjusts
			// the seekbar and b) once the user is done dragging the thumb
			// we will post one of these messages to the queue again and
			// this ensures that there will be exactly one message queued up.
			mHandler.removeMessages(SET_VOLUME);
		}

		public void onProgressChanged(SeekBar bar, int progress, boolean fromuser) {
			show(sDefaultTimeout);
//			mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
			// 当静音的时候，会出发这个时间，会导致currentVolume被记录下来再次恢复变成0的问题
			if (!isVolumeMute) {
//				currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC); // 获取当前值
				currentVolume = progress;
				if (mHandler != null) {
					if (mHandler.hasMessages(SET_VOLUME)) {
						mHandler.removeMessages(SET_VOLUME);
					}
					mHandler.sendEmptyMessageDelayed(SET_VOLUME, 50);
				} else {
					Log.e("medio", "msgHandler == null");
				}
				Log.i("volume", "onProgressChanged,currentVolume=" + currentVolume);
				mVolumeBar.setProgress(currentVolume);
			} else {
				mVolumeBar.setProgress(0);
				HardwareInterface.setVolume(0);
			}
			
/*			if (currentVolume > 0) {
				mMuteButtom.setBackgroundResource(R.drawable.music_volume);
			} else {
				isVolumeMute = true;
				mMuteButtom.setBackgroundResource(R.drawable.music_novolume);
			}*/
		}

		public void onStopTrackingTouch(SeekBar bar) {
			show(sDefaultTimeout);

//			mDragging = true;

			// By removing these pending progress messages we make sure
			// that a) we won't update the progress while the user adjusts
			// the seekbar and b) once the user is done dragging the thumb
			// we will post one of these messages to the queue again and
			// this ensures that there will be exactly one message queued up.
//			mHandler.removeMessages(SET_VOLUME);
		}
	};

	@Override
	public void setEnabled(boolean enabled) {
		if (mPauseButton != null) {
			mPauseButton.setEnabled(enabled);
		}
		if (mFfwdButton != null) {
			mFfwdButton.setEnabled(enabled);
		}
		if (mRewButton != null) {
			mRewButton.setEnabled(enabled);
		}
		if (mNextButton != null) {
			mNextButton.setEnabled(enabled && mNextListener != null);
		}
		if (mPrevButton != null) {
			mPrevButton.setEnabled(enabled && mPrevListener != null);
		}
		if (mProgress != null) {
			mProgress.setEnabled(enabled);
		}
		disableUnsupportedButtons();
		super.setEnabled(enabled);
	}

	private OnClickListener mRewListener = new OnClickListener() {
		public void onClick(View v) {
			if (mPlayer == null) {
				return;
			}

			int pos = mPlayer.getCurrentPosition();
			pos -= 5000; // milliseconds
			mPlayer.seekTo(pos);
			setProgress();

			show(sDefaultTimeout);
		}
	};

	private OnClickListener mFfwdListener = new OnClickListener() {
		public void onClick(View v) {
			if (mPlayer == null) {
				return;
			}

			int pos = mPlayer.getCurrentPosition();
			pos += 15000; // milliseconds
			mPlayer.seekTo(pos);
			setProgress();

			show(sDefaultTimeout);
		}
	};

	private void installPrevNextListeners() {
		if (mNextButton != null) {
			mNextButton.setOnClickListener(mNextListener);
			mNextButton.setEnabled(mNextListener != null);
		}

		if (mPrevButton != null) {
			mPrevButton.setOnClickListener(mPrevListener);
			mPrevButton.setEnabled(mPrevListener != null);
		}
	}

	public void setPrevNextListeners(OnClickListener next, OnClickListener prev) {
		mNextListener = next;
		mPrevListener = prev;
		mListenersSet = true;

		if (mRoot != null) {
			installPrevNextListeners();

			if (mNextButton != null && !mFromXml) {
				mNextButton.setVisibility(View.VISIBLE);
			}
			if (mPrevButton != null && !mFromXml) {
				mPrevButton.setVisibility(View.VISIBLE);
			}
		}
	}

	public interface MediaPlayerControl {
		void start();

		void pause();

		int getDuration();

		int getCurrentPosition();

		void seekTo(int pos);

		boolean isPlaying();

		int getBufferPercentage();

		boolean canPause();

		boolean canSeekBackward();

		boolean canSeekForward();

		boolean isFullScreen();

		void toggleFullScreen();
	}

	private static class MessageHandler extends Handler {
		private final WeakReference<NativeMediaController> mView;

		MessageHandler(NativeMediaController view) {
			mView = new WeakReference<NativeMediaController>(view);
		}

		@Override
		public void handleMessage(Message msg) {
			NativeMediaController view = mView.get();
			if (view == null || view.mPlayer == null) {
				return;
			}

			int pos;
			switch (msg.what) {
			case FADE_OUT:
				view.hide();
				break;
			case SHOW_PROGRESS:
				pos = view.setProgress();
				if (!view.mDragging && view.mShowing && view.mPlayer.isPlaying()) {
					msg = obtainMessage(SHOW_PROGRESS);
					sendMessageDelayed(msg, 1000 - (pos % 1000));
				}
				break;
			case SET_VOLUME:
				Log.i("VodActivity", "view.as.setVolume=" + view.currentVolume);
				HardwareInterface.setVolume(view.currentVolume);
				break;
			case SHOW_AD:
				if(AdData.getVod() != null && !AdData.getVod().getDetails().isEmpty()){
					for(AdDetail adl : AdData.getVod().getDetails()){
						if(adl.getType() == AdDetail.PIC){
							CloudAdDialog adDialog = new CloudAdDialog(view.mContext, R.style.adDialog);//创建Dialog并设置样式主题
							adDialog.setCanceledOnTouchOutside(true);//设置点击Dialog外部任意区域关闭Dialog
			//				adDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
							adDialog.setAd(AdData.getVod());	
							adDialog.show();
							break;
						}
					}
				}
				break;
			}
		}
	}
}
